import 'package:flutterdemo/library/sqflite/sqflite_helper.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';

final String _id = 'id';
final String _title = 'title';
final String _content = 'content';

class Article {
  int id;
  String title;
  String content;

  Article({this.id, this.title, this.content});

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      _title: title,
      _content: content,
    };
    return map;
  }

  Article.fromMap(Map<String, dynamic> map) {
    id = map[_id];
    title = map[_title];
    content = map[_content];
  }
}

class ArticleProvider {
  static const String _table = 'ta_article';
  String createSql =
      'CREATE TABLE $_table ($_id INTEGER PRIMARY KEY, $_title TEXT, $_content TEXT)';

  static ArticleProvider _instance;

  factory ArticleProvider() => _getInstance();

  static ArticleProvider _getInstance() {
    if (_instance == null) {
      _instance = ArticleProvider._();
    }
    return _instance;
  }

  //私有构造
  ArticleProvider._();

  Future insert(Article article) async {
    var _database = await SqfliteHelper().db;
    return await _database.insert(_table, article.toMap());
  }

  Future inserts(List<Article> articles) async {
    var _database = await SqfliteHelper().db;
    Batch batch = _database.batch();
    articles.forEach((element) {
      batch.insert(_table, element.toMap());
      print('${DateTime.now()}--${element.toMap()}');
    });
    return await batch.commit();
  }

  Future<Article> query(int id) async {
    var _database = await SqfliteHelper().db;
    List<Map> maps = await _database.query(
      _table,
      columns: [_id, _title, _content],
      where: '$_id=?',
      whereArgs: [id],
      limit: 1,
    );
    if (maps.length == 1) {
      return Article.fromMap(maps.first);
    } else {
      return null;
    }
  }

  Future<List<Article>> queryAll() async {
    var _database = await SqfliteHelper().db;
    List<Map> maps = await _database.query(_table);
    List<Article> list = [];
    maps.forEach((element) {
      list.add(Article.fromMap(element));
    });
    return list;
  }

  Future delete(int id) async {
    var _database = await SqfliteHelper().db;
    return await _database.delete(
      _table,
      where: '$_id=?',
      whereArgs: [id],
    );
  }

  Future update(Article article) async {
    var _database = await SqfliteHelper().db;
    return await _database.update(
      _table,
      article.toMap(),
    );
  }

  Future close() async {
    var _database = await SqfliteHelper().db;
    return await _database.close();
  }

  Future drop() async {
    String path = await getDatabasesPath();
    path = '$path/demo.db';
    return await deleteDatabase(path);
  }

  Future clear() async {
    var _database = await SqfliteHelper().db;
    await _database.delete(_table);
  }
}
